import { createRouter, createWebHashHistory } from 'vue-router'
// 一级路由
import Login from '../views/Login.vue'
import MainBox from '../views/MainBox.vue'
import NotFound from '@/views/notfound/NotFound.vue'
// 动态路由
import RouterConfig from '@/router/config'
// 动态变量
import { useRouterStore } from '../stores/useRouterStore'
import { useUserStore } from '@/stores/useUserStore'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/mainbox',
    name: 'mainbox',
    component: MainBox
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})


// 配置路由拦截
router.beforeEach((to, from, next) => {
  const { isGetterRouter } = useRouterStore()
  const { user } = useUserStore()
  // 判断打开打开的地址是login
  if (to.name === "login") {
    next()
  } else {
    // 判断是否有token
    if (!user.role) {
      // 没有跳转会登录界面
      next({
        path: "/login"
      })
    } else {
      // 如果第一次配置路由调用
      if (!isGetterRouter) {
        router.removeRoute("mainbox")
        ConfigRouter()
        next({
          path: to.fullPath
        })
      } else {
        next()
      }
    }
  }

})

const ConfigRouter = () => {
  let { changeRouter } = useRouterStore()
  router.addRoute({
    path: '/mainbox',
    name: 'mainbox',
    component: MainBox
  })
  // 动态添加路由
  RouterConfig.forEach(item => {
    checkRouter(item.path) && router.addRoute("mainbox", item)
  })
  // 重定向
  router.addRoute("mainbox", {
    path: "/",
    redirect: "/index"
  })
  // 404
  router.addRoute("mainbox", {
    path: "/:pathMatch(.*)*",
    component: NotFound
  })
  changeRouter(true)
}

// 判断添加权限
const checkRouter = (path) => {
  const { user } = useUserStore()

  return user.role.rights.includes(path)
}

export default router
